import 'dart:convert';

import 'package:dropdown_button2/dropdown_button2.dart';
import 'package:enterprise_v8/app/components/toast_widget.dart';
import 'package:enterprise_v8/app/core/core.dart';
import 'package:enterprise_v8/app/core/ext/widget_extension.dart';
import 'package:enterprise_v8/app/data/entities/auth/user_login_entity.dart';
import 'package:enterprise_v8/generated/assets.gen.dart';
import 'package:enterprise_v8/modules/auth/login/controller.dart';

/// 登录页面
class LoginPage extends StatelessWidget {
  LoginPage({super.key});

  final controller = Get.put(LoginController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
        init: controller,
        builder: (_) {
          return PopScope(
              canPop: controller.isPopPage(),
              onPopInvoked: (didPop) {
                if (!didPop) {
                  controller.lastPressedAt = DateTime.now();
                  AppToast.showWarning('再次点击，立即退出App');
                  controller.update();
                }
              },
              child: Scaffold(
                  body: Stack(
                children: [
                  // 渐变绿色背景
                  Assets.svg.loginBg.svg(width: AppDimens.sw),
                  Column(
                    children: [
                      Container(
                        height: 60.w,
                      ),
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.symmetric(horizontal: 30.w),
                          child: SingleChildScrollView(
                            child: Column(
                              children: [
                                AppGaps.vGap60,
                                Row(
                                  children: [
                                    Text(
                                      '欢迎登录\n企业智能管控平台',
                                      style: TextStyle(
                                        fontSize: AppDimens.sp30,
                                        fontWeight: FontWeight.w500,
                                        color: const Color(0xff154A86),
                                      ),
                                    ),
                                  ],
                                ),
                                AppGaps.vGap40,
                                _userNameInput(),
                                AppGaps.vGap20,
                                _passwordInput(),
                                AppGaps.vGap20,
                                _verifyCodeInput(),
                                AppGaps.vGap20,
                                _rememberPwd(),
                                AppGaps.vGap60,
                                _loginButton(),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              )));
        });
  }

  /// 账号输入框
  Widget _userNameInput() {
    return SizedBox(
      child: Obx(() {
        return TextField(
          focusNode: controller.userNameNode,
          controller: controller.textEditingControllerUserName,
          decoration: InputDecoration(
            hintText: '请输入您的账号',
            hintStyle: const TextStyle(
              color: Color(0xff4D5956),
              fontWeight: FontWeight.w400,
              fontSize: 14,
            ),
            suffixIcon: controller.userNameHasFocus.value
                ? IconButton(
                    icon: const Icon(Icons.clear),
                    onPressed: () {
                      controller.textEditingControllerUserName.clear();
                    },
                  )
                : _historyDrop(),
            label: const Text('账号',
                style: TextStyle(
                  color: Color(0xff4D5956),
                  fontWeight: FontWeight.w400,
                  fontSize: 14,
                )),
          ),
        );
      }),
    );
  }

  /// 历史账号列表
  Widget _historyDrop() {
    return DropdownButtonHideUnderline(
        child: DropdownButton2<UserLoginEntity>(
      items: controller.userList.map((item) {
        return DropdownMenuItem<UserLoginEntity>(
            value: item,
            child: Row(
              children: [
                Expanded(
                  child: Text(
                    item.userName,
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                    style: TextStyle(
                      fontSize: 18.w,
                      fontWeight: FontWeight.w400,
                      color: const Color(0xff434343),
                    ),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: () {
                    controller.removeHistoryUser(item);
                  },
                )
              ],
            ));
      }).toList(),
      //选择框样式
      dropdownStyleData: DropdownStyleData(
        maxHeight: 300.w,
        width: 350.w,
        padding: EdgeInsets.symmetric(vertical: 10.w),
        decoration: BoxDecoration(
          // 黑色边框
          border: Border.all(color: const Color(0xff434343), width: 0.5),
          borderRadius: BorderRadius.circular(10.w),
          color: const Color(0xffffffff),
        ),
        // offset: const Offset(-60, 0),
        offset: Offset(-285.w, 0),
      ),
      customButton: const Icon(
        Icons.arrow_drop_down,
      ),
      onChanged: (value) {
        if (value != null) {
          controller.selectHistoryUser(value);
        }
      },
    ));
  }

  /// 密码输入框
  Widget _passwordInput() {
    return SizedBox(
      child: Obx(() {
        return TextField(
          focusNode: controller.passwordNode,
          controller: controller.textEditingControllerPassword,
          obscureText: true,
          decoration: InputDecoration(
            hintText: '请输入密码',
            hintStyle: const TextStyle(
              color: Color(0xff4D5956),
              fontWeight: FontWeight.w400,
              fontSize: 14,
            ),
            suffixIcon: controller.passwordHasFocus.value
                ? IconButton(
                    icon: const Icon(Icons.clear),
                    onPressed: () {
                      controller.textEditingControllerPassword.clear();
                    },
                  )
                : null,
            label: Wrap(
              crossAxisAlignment: WrapCrossAlignment.center,
              children: [
                AppGaps.hGap8,
                const Text('密码',
                    style: TextStyle(
                      color: Color(0xff4D5956),
                      fontWeight: FontWeight.w400,
                      fontSize: 14,
                    )),
              ],
            ),
          ),
        );
      }),
    );
  }

  /// 验证码输入框 左边输入框,右边验证码,点击刷新验证码
  Widget _verifyCodeInput() {
    return SizedBox(
      child: Row(
        children: [
          Expanded(
            child: TextField(
              focusNode: controller.verifyCodeNode,
              controller: controller.textEditingControllerVerifyCode,
              decoration: InputDecoration(
                hintText: '请输入验证码',
                hintStyle: const TextStyle(
                  color: Color(0xff4D5956),
                  fontWeight: FontWeight.w400,
                  fontSize: 14,
                ),
                label: Wrap(
                  crossAxisAlignment: WrapCrossAlignment.center,
                  children: [
                    AppGaps.hGap8,
                    const Text('验证码',
                        style: TextStyle(
                          color: Color(0xff4D5956),
                          fontWeight: FontWeight.w400,
                          fontSize: 14,
                        )),
                  ],
                ),
              ),
            ),
          ),
          AppGaps.hGap8,
          Obx(() {
            return Container(
              width: 100.w,
              height: 40.w,
              alignment: Alignment.center,
              decoration: const BoxDecoration(
                color: Color(0xff5C6DFF),
              ),
              child: Image.memory(
                base64Decode(controller.verifyCodeBase64.value),
                width: 100.w,
                height: 40.w,
                fit: BoxFit.fill,
              ),
            ).clickOnce(controller.refreshVerifyCode);
          }),
        ],
      ),
    );
  }

  /// 记住密码 和 忘记密码
  Widget _rememberPwd() {
    return Row(
      children: [
        Row(
          children: [
            Obx(() => Checkbox(
                  value: controller.rememberPwd.value,
                  onChanged: (value) {
                    controller.onRememberPwdChanged(value ?? false);
                  },
                  activeColor: const Color(0xff5C6DFF),
                  checkColor: const Color(0xffffffff),
                  materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                )),
            AppGaps.hGap4,
            Text(
              '记住账户密码',
              style: TextStyle(
                height: 1.2,
                color: const Color(0xff4D5956),
                fontSize: 12.sp,
              ),
            ),
          ],
        ).clickOnce(() {
          controller.onRememberPwdChanged(!controller.rememberPwd.value);
        }),
        Expanded(child: Container()),
        Text(
          '忘记密码?',
          style: TextStyle(
            height: 1.2,
            color: const Color(0xff5C6DFF),
            fontSize: 12.sp,
          ),
        ).clickOnce(controller.forgetPwd),
      ],
    );
  }

  /// 登录按钮
  Widget _loginButton() {
    return GestureDetector(
        onTap: controller.loginDo,
        child: Center(
          child: Obx(() {
            return AnimatedContainer(
              duration: const Duration(milliseconds: 200),
              width: controller.isClick.value ? 48.w : AppDimens.sw,
              height: 48.w,
              alignment: Alignment.center,
              decoration: BoxDecoration(color: const Color(0xff5C6DFF), borderRadius: BorderRadius.all(Radius.circular(44.w))),
              child: Container(
                width: 48.w,
                height: 48.w,
                alignment: Alignment.center,
                child: AnimatedCrossFade(
                  firstChild: Text(
                    '登录',
                    style: TextStyle(
                      color: const Color(0xfff5f5f5),
                      fontWeight: FontWeight.w400,
                      fontSize: 18.sp,
                    ),
                  ),
                  secondChild: Container(
                    padding: EdgeInsets.all(12.w),
                    child: const CircularProgressIndicator(
                      valueColor: AlwaysStoppedAnimation<Color>(Color(0xfff5f5f5)),
                    ),
                  ),
                  crossFadeState: controller.isClick.value ? CrossFadeState.showSecond : CrossFadeState.showFirst,
                  firstCurve: Curves.easeInOut,
                  secondCurve: Curves.ease,
                  duration: const Duration(milliseconds: 500),
                ),
              ),
            );
          }),
        ));
  }
}
